package cn.liyicun.cp.cpweb.service.cp;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.liyicun.cp.cpweb.entity.GetApicp;
import cn.liyicun.cp.cpweb.entity.GetApicpExample;
import cn.liyicun.cp.cpweb.entity.GetApicpKey;
import cn.liyicun.cp.cpweb.mapper.GetApicpMapper;
import cn.liyicun.cp.cpweb.service.BaseService;
import cn.liyicun.cp.cpweb.service.ExpectInfoService;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class GetApicpService extends BaseService {
    private static Logger log = LoggerFactory.getLogger(GetApicpService.class);

    @Autowired
    GetApicpMapper getApicpMapper;
    @Autowired
    ExpectInfoService expectInfoService;

    public void execute(String code, String url) {
        String str = null;
        try {
            str = HttpUtil.downloadString(url, "utf-8");
        } catch (Exception e) {
            System.err.println(code + "\t" + url);
            e.printStackTrace();
//            api.apicp.cn api.jiutoumao.cn
            return;
        }

        JSONObject json = JSONUtil.parseObj(str);
        List<GetApicp> list = JSONUtil.toList(json.getJSONArray("data"), GetApicp.class);
        //倒序
        Collections.reverse(list);
        for (GetApicp cp : list) {
            cp.setCode(code);
        }
    }

    public void one(GetApicp cp ){
        GetApicpKey key = new GetApicpKey();
        key.setCode(cp.getCode());
        key.setExpect(cp.getExpect());
        GetApicp data = getApicpMapper.selectByPrimaryKey(key);
        if (data == null) {
            cp.setCreateTime(new Date());
            getApicpMapper.insertSelective(cp);
            log.info("{}", JSONUtil.toJsonStr(cp));
            expectInfoService.openPrize(cp.getCode(),Long.valueOf(cp.getExpect()),cp.getOpencode(),cp.getOpentime());
        }
    }



    public List<GetApicp> list(String code, int page, int limit) {
        GetApicpExample exa = new GetApicpExample();
        exa.createCriteria().andCodeEqualTo(code);
        exa.setOrderByClause("expect desc");
        RowBounds row = new RowBounds((page - 1) * limit, limit);
        return getApicpMapper.selectByExampleWithRowbounds(exa, row);
    }
}
